import React, { useEffect } from 'react'
import { useNavigate } from 'react-router-dom'
import './usLogin.less'
import logo from '../../assets/images/logo.png'
import {
  UserOutlined,
  LockOutlined
} from '@ant-design/icons'

import {
  Button,
  Checkbox,
  Form,
  Input,
  message
} from 'antd'

import { postLogin } from "@/api/user"
import { savaUser, getUser } from "@/utils/storage"

export default function Login() {
  const navigate = useNavigate()
  function loginMeg(jump = {}) {
    navigate(jump.route, jump.option)
    jump.tips && message.info(jump.tips)
    return undefined
  }

  useEffect(() => {
    const userInfo = getUser()
    if (userInfo._id) {
      const jump = {
        route: "/admin",
        option: { replace: true },
      }
      return loginMeg(jump)
    }
  })




  const onFinish = async (values) => {
    const { password, remember, username } = values
    if (!remember) return message.info("请同意协议")
    const userInfo = await postLogin({ username, password })

    if (!userInfo.status) {
      savaUser(userInfo.data)
      const jump = {
        route: "/admin",
        option: { replace: true },
        tips: "登陆成功"
      }
      loginMeg(jump)
    }
  };

  const onFinishFailed = (errorInfo) => {
    console.log('登陆失败:', errorInfo);
  };

  return (
    <div className="login">
      <header className="login-header">
        <img src={logo} alt="logo" />
        <h1>React项目: 后台管理系统</h1>
      </header>
      <section className="login-content">
        <h2>用户登陆</h2>

        <Form
          wrapperCol={{ span: 24 }}
          name="basic"
          autoComplete="off"
          onFinish={onFinish}
          onFinishFailed={onFinishFailed}
        >
          <Form.Item
            name="username"
            rules={
              [
                { required: true, message: '请输入用户名' },
                { min: 4, message: '至少4位' },
                { max: 12, message: '最多12位' },
                { pattern: /^[a-zA-Z0-9_]+$/, message: '用户名必须英文,数字或下划线组成' }
              ]
            }
          >
            <Input prefix={<UserOutlined />} />
          </Form.Item>

          <Form.Item
            name="password"
            rules={
              [
                () => ({
                  validator(_, value) {
                    if (!value) {
                      return Promise.reject(new Error('请输入密码'));
                    }
                    else if (value.length < 4) {
                      return Promise.reject(new Error('输入至少4位'));
                    }
                    else if (value.length > 12) {
                      return Promise.reject(new Error('输入至多12位'));
                    }
                    else if (!/^[a-zA-Z0-9_]+$/.test(value)) {
                      return Promise.reject(new Error('用户名必须英文,数字或下划线组成'));
                    }
                    else {
                      return Promise.resolve();
                    }
                  },
                })
              ]
            }
          >
            <Input.Password autoComplete="off" prefix={<LockOutlined />} />
          </Form.Item>

          <Form.Item name="remember" valuePropName="checked" wrapperCol={{ offset: 8, span: 24 }}>
            <Checkbox>是否同意本协议</Checkbox>
          </Form.Item>

          <Form.Item wrapperCol={{ span: 24 }}>
            <Button type="primary" htmlType="submit" style={{ width: "100%" }}>
              登陆
            </Button>
          </Form.Item>
        </Form>
      </section>
    </div>
  )
}
